#!/usr/bin/env python3
"""
设置飞书webhook的管理命令
"""
from django.core.management.base import BaseCommand
from django.contrib.auth import get_user_model
from projects.models import Project, Webhook

User = get_user_model()

class Command(BaseCommand):
    help = '设置项目的飞书webhook配置'
    
    def add_arguments(self, parser):
        parser.add_argument(
            '--project-id',
            type=int,
            required=True,
            help='项目ID'
        )
        parser.add_argument(
            '--webhook-url',
            type=str,
            required=True,
            help='飞书机器人的webhook URL'
        )
        parser.add_argument(
            '--name',
            type=str,
            default='飞书消息推送',
            help='webhook名称'
        )
        parser.add_argument(
            '--events',
            type=str,
            default='announcement,webhook',
            help='触发事件，用逗号分隔（announcement,webhook,alarm,push）'
        )
    
    def handle(self, *args, **options):
        project_id = options['project_id']
        webhook_url = options['webhook_url']
        name = options['name']
        events_str = options['events']
        
        try:
            project = Project.objects.get(id=project_id)
            
            # 解析事件列表
            events = [event.strip() for event in events_str.split(',')]
            valid_events = ['announcement', 'webhook', 'alarm', 'push']
            events = [event for event in events if event in valid_events]
            
            if not events:
                self.stdout.write(
                    self.style.ERROR('无效的事件类型，请使用：announcement,webhook,alarm,push')
                )
                return
            
            # 创建或更新飞书webhook
            webhook, created = Webhook.objects.get_or_create(
                project=project,
                url=webhook_url,
                defaults={
                    'name': name,
                    'channel': 'feishu',
                    'events': events,
                    'is_active': True
                }
            )
            
            if created:
                self.stdout.write(
                    self.style.SUCCESS(f'✅ 成功创建飞书webhook: {name}')
                )
            else:
                # 更新现有webhook
                webhook.name = name
                webhook.channel = 'feishu'
                webhook.events = events
                webhook.is_active = True
                webhook.save()
                self.stdout.write(
                    self.style.SUCCESS(f'✅ 成功更新飞书webhook: {name}')
                )
            
            self.stdout.write(f'   项目: {project.name} (ID: {project.id})')
            self.stdout.write(f'   URL: {webhook_url}')
            self.stdout.write(f'   事件: {", ".join(events)}')
            
        except Project.DoesNotExist:
            self.stdout.write(
                self.style.ERROR(f'❌ 项目ID {project_id} 不存在')
            )
        except Exception as e:
            self.stdout.write(
                self.style.ERROR(f'❌ 设置失败: {str(e)}')
            )